<!DOCTYPE html>
<!-- saved from url=(0049)https://getbootstrap.com/docs/4.0/examples/cover/ -->
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="https://getbootstrap.com/docs/4.0/assets/img/favicons/favicon.ico">

    <title>Stonk Market</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/cover/">

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


    <!-- Custom styles for this template -->
    <link href="./css/cover.css" rel="stylesheet">
  </head>

  <body class="text-center" data-gr-c-s-loaded="true">

    <div class="cover-container d-flex h-100 p-3 mx-auto flex-column">
      <header class="masthead mb-auto">
        <div class="inner">
          <h3 class="masthead-brand">Stonk Market</h3>
          <nav class="nav nav-masthead justify-content-center">
            <a class="nav-link active" href="https://getbootstrap.com/docs/4.0/examples/cover/#">Home</a>
            <a class="nav-link" href="https://twitter.com/alcapwnctf">Contact</a>
          </nav>
        </div>
      </header>

      <main role="main" class="inner cover">
        <h1 class="cover-heading">Go to the stonk market</h1>
        <div class='row'>
          <div class='col'>
              <form id='registerAndLoginForm'>
                <div class="form-group">
                  <label for="Username">Username</label>
                  <input type="text" class="form-control" id="username" aria-describedby="emailHelp" placeholder="Enter username">
                </div>
                <div class="form-group">
                  <label for="password">Password</label>
                  <input type="password" class="form-control" id="password" placeholder="Password">
                </div>
              </form>
              <button onclick="login(this)" class="btn btn-lg btn-primary">Login</button>
              <button onclick="register(this)" class="btn btn-lg btn-warning">Register</button>
          </div>
        </div>
        <div class='row p-3'>
            <div class='col'>
                <div id='content'>
  
                </div>
            </div>
        </div>
      </main>

      <footer class="mastfoot mt-auto">
        <div class="inner">
          <p>Cover template for <a href="https://getbootstrap.com/">Bootstrap</a>, by <a href="https://twitter.com/mdo">@mdo</a>.</p>
        </div>
      </footer>
    </div>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <script>
        form = document.querySelector('#loginForm')
        
        const API_ROOT = ""
        
        const API_LOGIN_ENDPOINT = "/login"
        const API_REGISTER_ENDPOINT = "/register"
        
        const API_V1 = "/api"

        const FETCH_OPTIONS = {
          fund_prefix: "fund",
        }

        const API_LIST_ENDPOINT = "/list"
        const API_FETCH_ENDPOINT = "/fetch"
        const API_FLAG_ENDPOINT = "/flag"
        const API_FETCH_VALUE_ENDPOINT = "/value?query="

        const getJson = async (version, endpoint) => {
            let req = await fetch(`${API_ROOT}${version}${endpoint}`)
            return [req.status, await req.json()]
        }

        const postJson = async (version, endpoint, payload) => {
            let req = await fetch(`${API_ROOT}${version}${endpoint}`, {
                method: 'POST',
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json'
                },
                credentials: "include",
                body: JSON.stringify(payload)
            });

            return [req.status, await req.json()]
        }
        
        const getUsername = () => {
            return document.querySelector('#username').value
        }

        const getPassword = () => {
            return document.querySelector('#password').value
        }
        
        const setContent = (htmlData) => {
            document.querySelector("#content").innerHTML = htmlData
        }

        const setValue = async (evt) => {
          const cell = row.getElementsByTagName("td")[0];
          const key = cell.innerText
          
          const [status, valJson] = await getJson(API_V1, `${API_FETCH_ENDPOINT}/${FETCH_OPTIONS.fund_prefix}${API_FETCH_VALUE_ENDPOINT}${key}`)

          if (status === 200) {
            setContent(`<span>${valJson.key}: ${valJson.value}</span>`)
          }
        }

        const setFunds = async () => {
          const [status, fundJson] = await getJson(API_V1, `${API_FETCH_ENDPOINT}/${FETCH_OPTIONS.fund_prefix}`)

          if (status === 200) {
            let html = `<table><tr><th>Fund Name</th></tr>`
  
            for (const fund of fundJson.items) {
              html += `<tr onclick="setValue" ><td>${fund}</td></tr>`
            }
  
            html += "</table>"
  
            setContent(html)
          }          
        }

        const delay = ms => new Promise(res => setTimeout(res, ms));
        
        async function register(evt) {
            let username = getUsername()
            let password = getPassword()

            let payload = {
                "username": username,
                "password": password
            }

            console.log(payload)

            let [status, registerReq] = await postJson("/api", API_REGISTER_ENDPOINT, payload)
            if (status === 200) {
                setContent("<span>Registration Successful!</span>")
                await delay(500)
                setFunds()
            } else {
                setContent(`<span>${registerReq.detail}</span>`)
            }
        }

        async function login(evt) {
            let username = getUsername()
            let password = getPassword()

            let payload = {
                "username": username,
                "password": password
            }

            console.log(payload)

            let [status, loginReq] = await postJson("/api", API_LOGIN_ENDPOINT, payload)
            if (status === 200) {
                setContent("<span>Login Successful</span>")
                await delay(500)
                setFunds()
            } else {
                setContent(`<span>${loginReq.detail}</span>`)
            }
        }
    </script>
</body>
</html>
